package com.longcai.service.impl.nearby;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.longcai.bean.ApiResult;
import com.longcai.entity.homepage.ClyjUserSearch;
import com.longcai.entity.homepage.GoodsClass;
import com.longcai.entity.nearby.ClyjNearbyShops;
import com.longcai.entity.nearby.ClyjShopsTrading;
import com.longcai.entity.nearby.ClyjTradingArea;
import com.longcai.mapper.homepage.GoodsClassMapper;
import com.longcai.mapper.nearby.ClyjNearbyShopsMapper;
import com.longcai.mapper.nearby.ClyjShopsTradingMapper;
import com.longcai.mapper.nearby.ClyjTradingAreaMapper;
import com.longcai.service.homepage.ClyjUserHotsearchService;
import com.longcai.service.homepage.ClyjUserSearchService;
import com.longcai.service.nearby.ClyjNearbyShopsService;
import com.longcai.util.DistanceUtil;
import com.longcai.util.OSSUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.*;

/**
 * <p>
 * 附近商铺 服务实现类
 * </p>
 *
 * @author M
 * @since 2019-03-26
 */
@Service
public class ClyjNearbyShopsServiceImpl extends ServiceImpl<ClyjNearbyShopsMapper, ClyjNearbyShops> implements ClyjNearbyShopsService {
	private Logger logger = LoggerFactory.getLogger(getClass());

	@Autowired
	private GoodsClassMapper classMapper;

	@Autowired
	private ClyjNearbyShopsMapper clyjNearbyShopsMapper;
	@Autowired
	private ClyjUserSearchService clyjUserSearchService;
	@Autowired
	private ClyjUserSearchService bannerService;
	@Autowired
	private ClyjUserHotsearchService clyjUserHotsearchService;
	@Autowired
	private GoodsClassMapper goodsClassMapper;
	@Autowired
	private ClyjShopsTradingMapper clyjShopsTradingMapper;
	@Autowired
	private ClyjTradingAreaMapper clyjTradingAreaMapper;

	/**
	 * 查询附近页面分类
	 *
	 * @return
	 */
	@Override
	public ApiResult getShopClass() {

		try {
			QueryWrapper<GoodsClass> queryWrapper = new QueryWrapper<>();
			queryWrapper.eq("type", "2");
			queryWrapper.isNull(true, "p_id");
			List<GoodsClass> list = this.classMapper.selectList(queryWrapper);
			logger.debug("查询成功+++++++++", list);
			return ApiResult.success(list);
		} catch (Exception e) {
			logger.debug("查询失败");
			e.printStackTrace();
			return ApiResult.fail("查询失败" + e.getMessage());
		}
	}

	/**
	 * 获取附近首页分类子类
	 *
	 * @param shopsclass
	 * @return
	 */
	@Override
	public ApiResult getShopsClass(String shopsclass) {
		try {
			QueryWrapper<GoodsClass> queryWrapper = new QueryWrapper<>();
			queryWrapper.eq("type", "2");
			queryWrapper.eq("p_id", shopsclass);
			List<GoodsClass> list = this.classMapper.selectList(queryWrapper);
			logger.debug("查询成功+++++++++", list);
			return ApiResult.success(list);
		} catch (Exception e) {
			logger.debug("查询失败+++++++++");
			e.printStackTrace();
			return ApiResult.fail("查询失败" + e.getMessage());
		}
	}

	/**
	 * 查询附近店铺列表
	 *
	 * @return
	 */
	@Override
	public ApiResult getShops(String country) {
		try {
			QueryWrapper<ClyjNearbyShops> queryWrapper = new QueryWrapper<>();
			queryWrapper.eq("shop_country", country);
			queryWrapper.orderByDesc("sales_volume");
			List<ClyjNearbyShops> list = this.clyjNearbyShopsMapper.selectList(queryWrapper);
			logger.debug("查询成功+++++++++", list);
			return ApiResult.success(list);
		} catch (Exception e) {
			logger.debug("查询失败+++++++++");
			e.printStackTrace();
			return ApiResult.fail("查询失败" + e.getMessage());
		}
	}

	/**
	 * 查询附近店铺详情
	 *
	 * @param shopsid
	 * @return
	 */
	@Override
	public ApiResult getShopsInfo(String shopsid) {
		try {
			QueryWrapper<ClyjNearbyShops> queryWrapper = new QueryWrapper<>();
			queryWrapper.eq("shops_id", shopsid);
			List<ClyjNearbyShops> list = this.clyjNearbyShopsMapper.selectList(queryWrapper);
			logger.debug("查询成功++++++++++++", list);
			return ApiResult.success(list);
		} catch (Exception e) {
			logger.error("查询失败");
			e.printStackTrace();
			return ApiResult.fail("查询失败" + e.getMessage());
		}
	}

	/**
	 * 附近店铺关键字搜索
	 *
	 * @param keyvalue
	 * @return
	 */
	@Override
	public ApiResult searchShop(String keyvalue, String lng, String lat, String country, String userId) {
		Map map = new HashMap();
		try {
			//查询商圈
			List list1 = new ArrayList();
			List<ClyjShopsTrading> clyjShopsTradings = this.clyjShopsTradingMapper.select(keyvalue);
			for (ClyjShopsTrading clyjShopsTrading : clyjShopsTradings) {
				list1.add(clyjShopsTrading.getShopsId());
			}
			//查询店铺类型对应id
			List<String> list = this.clyjUserSearchService.findTypeTree(keyvalue);
			map.put("list", list);
			map.put("keyvalue", keyvalue);
			map.put("country", country);
			map.put("list1", list1);
			List<ClyjNearbyShops> clyjNearbyShopsList = this.clyjNearbyShopsMapper.searchShop(map);
			for (ClyjNearbyShops clyjNearbyShops : clyjNearbyShopsList) {
				if (clyjNearbyShops.getLng() == null || clyjNearbyShops.getLng() == "" || clyjNearbyShops.getLat() == null || clyjNearbyShops.getLat() == "") {
					continue;
				}
				//根据店铺经纬度查询距离
				String algorithm = DistanceUtil.algorithm(Double.valueOf(clyjNearbyShops.getLng()), Double.valueOf(clyjNearbyShops.getLat()), Double.valueOf(lng), Double.valueOf(lat));
				clyjNearbyShops.setBusinessPatent(algorithm);
			}
			//根据距离将店铺排序
			Collections.sort(clyjNearbyShopsList);
			logger.debug("查询成功+++++++++++++++", clyjNearbyShopsList);
			if (userId == null || userId.equals("")) {
				//存储用户搜索记录
				QueryWrapper<ClyjUserSearch> queryWrapper = new QueryWrapper<ClyjUserSearch>();
				queryWrapper.eq("user_id", userId);
				queryWrapper.eq("search_name", keyvalue);
				queryWrapper.orderByDesc("search_time");
				List<ClyjUserSearch> selectList = bannerService.selectList(queryWrapper);
				//查询该记录是否已经存在
				if (selectList != null && selectList.size() > 0) {
					return ApiResult.success(clyjNearbyShopsList);
				}
				//不存在则插入数据
				ClyjUserSearch clyjUserSearch = new ClyjUserSearch();
				clyjUserSearch.setId(UUID.randomUUID().toString().replace("-", ""));
				clyjUserSearch.setSearchName(keyvalue);
				clyjUserSearch.setUserId(userId);
				clyjUserSearch.setSearchTime(new Date());
				clyjUserSearch.setFlag(1);
				bannerService.insert(clyjUserSearch);
			}
			//存储热门搜索
			this.clyjUserHotsearchService.insertnearsearch(keyvalue);
			return ApiResult.success(clyjNearbyShopsList);
		} catch (Exception e) {
			logger.error("查询失败");
			e.printStackTrace();
			return ApiResult.fail("查询失败" + e.getMessage());
		}
	}

	/**
	 * 附近店铺经纬度查询
	 *
	 * @param lng
	 * @param lat
	 * @param country
	 * @return
	 */
	@Override
	public ApiResult getShopsByAddress(String lng, String lat, String country, String distance) {
		QueryWrapper<ClyjNearbyShops> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("shop_country", country);
		queryWrapper.orderByDesc("sales_volume");
		//根据区县查询出所有店铺
		List<ClyjNearbyShops> list = this.clyjNearbyShopsMapper.selectList(queryWrapper);
		if (distance != null && !distance.equals("")) {
			List<ClyjNearbyShops> listTemp = new ArrayList<ClyjNearbyShops>();
			for (ClyjNearbyShops clyjNearbyShops : list) {
				if (clyjNearbyShops.getLng() == null || clyjNearbyShops.getLng() == "" || clyjNearbyShops.getLat() == null || clyjNearbyShops.getLat() == "") {
					continue;
				}
				//根据店铺经纬度查询距离
				String algorithm = DistanceUtil.algorithm(Double.valueOf(clyjNearbyShops.getLng()), Double.valueOf(clyjNearbyShops.getLat()), Double.valueOf(lng), Double.valueOf(lat));
				clyjNearbyShops.setBusinessPatent(algorithm);
				if (Integer.valueOf(algorithm).compareTo(Integer.valueOf(distance)) <= 0) {
					listTemp.add(clyjNearbyShops);
				}
			}
			list = listTemp;
		} else {
			for (ClyjNearbyShops clyjNearbyShops : list) {
				if (clyjNearbyShops.getLng() == null || clyjNearbyShops.getLng() == "" || clyjNearbyShops.getLat() == null || clyjNearbyShops.getLat() == "") {
					continue;
				}
				//根据店铺经纬度查询距离
				String algorithm = DistanceUtil.algorithm(Double.valueOf(clyjNearbyShops.getLng()), Double.valueOf(clyjNearbyShops.getLat()), Double.valueOf(lng), Double.valueOf(lat));
				clyjNearbyShops.setBusinessPatent(algorithm);
			}
		}
		//根据距离将店铺排序
		Collections.sort(list);

		return ApiResult.success(list);
	}

	/**
	 * 根据商圈查询店铺
	 *
	 * @param tradingid
	 * @return
	 */
	public ApiResult getShopByTradingArea(String tradingid) {
		try {
			//查询该商圈店铺类型对应id
			QueryWrapper<ClyjShopsTrading> queryWrapper = new QueryWrapper<>();
			queryWrapper.select("shops_id");
			queryWrapper.eq("trading_id", tradingid);
			List<ClyjShopsTrading> ClyjShopsTradingList = this.clyjShopsTradingMapper.selectList(queryWrapper);

			List list = new ArrayList();
			for (ClyjShopsTrading clyjShopsTrading : ClyjShopsTradingList) {
				list.add(clyjShopsTrading.getShopsId());
			}
			Map map = new HashMap();
			map.put("list", list);
			List<ClyjNearbyShops> clyjNearbyShopsList = this.clyjNearbyShopsMapper.searchShopByShopIdList(map);
			logger.debug("查询成功");
			return ApiResult.success(clyjNearbyShopsList);
		} catch (Exception e) {
			logger.error("查询失败");
			e.printStackTrace();
			return ApiResult.fail("查询失败" + e.getMessage());
		}

	}

	/**
	 * 根据商铺类型查询
	 *
	 * @param shopType
	 * @return
	 */
	public ApiResult getShopsByShopType(String shopType) {
		try {
			QueryWrapper<ClyjNearbyShops> queryWrapper = new QueryWrapper<>();
			queryWrapper.eq("shops_type", shopType);
			List<ClyjNearbyShops> clyjNearbyShopsList = this.clyjNearbyShopsMapper.selectList(queryWrapper);
			return ApiResult.success(clyjNearbyShopsList);
		} catch (Exception e) {
			logger.error("查询失败");
			e.printStackTrace();
			return ApiResult.fail("查询失败" + e.getMessage());
		}
	}

	/**
	 * 搜索显示候选词
	 *
	 * @param keyvalue
	 * @return
	 */
	@Override
	public Map<String, Object> getSearchNearkey(String keyvalue) {
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			//关键字模糊查询类型
			List goodsClasses = this.goodsClassMapper.selectname(keyvalue);
			result.put("goodsClasses", goodsClasses);
			//关键字搜索店铺名称
			List goods = this.clyjNearbyShopsMapper.selectGoodsName(keyvalue);
			result.put("goods", goods);
			//搜索商圈
			List<ClyjTradingArea> clyjTradingAreaList = this.clyjTradingAreaMapper.selectTrading(keyvalue);
			result.put("clyjTradingAreaList", clyjTradingAreaList);
			return result;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	/**
	 * 添加店铺
	 */


	@Override
	public boolean addShops(JSONObject params, MultipartFile aptitudePicture, MultipartFile corporateCardPic,
			MultipartFile corporateBankCardPic, MultipartFile headPicture, MultipartFile pictureIn,MultipartFile corporateCardPicBack, MultipartFile threeCardPic) {
		ClyjNearbyShops cns=new ClyjNearbyShops();
		cns.setShopsId(UUID.randomUUID().toString().replace("-", ""));
		cns.setShopsName(params.getString("shopsName"));
		cns.setCorporateName(params.getString("corporateName"));
		cns.setCorporateCard(params.getString("corporateCard"));
		cns.setShopProvince(params.getString("shopProvince"));
		cns.setShopCity(params.getString("shopCity"));
		cns.setShopCountry(params.getString("shopCountry"));
		cns.setShopsAddress(params.getString("shopsAddress"));
		cns.setLng(params.getString("lng"));
		cns.setLat(params.getString("lat"));
		cns.setAptitudeTime(params.getString("aptitudeTime"));
		cns.setCorporateBankCard(params.getString("corporateBankCard"));
		cns.setCorporateBankName(params.getString("corporateBankName"));
		cns.setCorporateBankDetail(params.getString("corporateBankDetail"));
		cns.setBankPhone(params.getString("bankPhone"));
		cns.setCorporateEmail(params.getString("corporateEmail"));
		cns.setUnifiedCode(params.getString("unifiedCode"));
		cns.setParentBankId(params.getString("parentBankId"));
		cns.setArtifNm(params.getString("ArtifNm"));
		cns.setCompanyOrgNum(params.getString("companyOrgNum"));
		cns.setTaxNum(params.getString("taxNum"));
		cns.setBusinessLicense(params.getString("businessLicense"));
		if (aptitudePicture != null) {
			//文档上传oss
			try {
				String fileName = aptitudePicture.getOriginalFilename();
				String pox = fileName.substring(fileName.lastIndexOf(".") + 1);
				InputStream inputStream = aptitudePicture.getInputStream();
				Map<String, Object> uploadByInputStream = OSSUtils.uploadByInputStream(inputStream, pox, "CLYJ/USER/");
				cns.setAptitudePicture(uploadByInputStream.get("path").toString());
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		if (threeCardPic != null) {
			//文档上传oss
			try {
				String fileName = aptitudePicture.getOriginalFilename();
				String pox = fileName.substring(fileName.lastIndexOf(".") + 1);
				InputStream inputStream = aptitudePicture.getInputStream();
				Map<String, Object> uploadByInputStream = OSSUtils.uploadByInputStream(inputStream, pox, "CLYJ/USER/");
				cns.setThreeCardPic(uploadByInputStream.get("path").toString());
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		if (corporateCardPic != null) {
			//文档上传oss
			try {
				String fileName = corporateCardPic.getOriginalFilename();
				String pox = fileName.substring(fileName.lastIndexOf(".") + 1);
				InputStream inputStream = corporateCardPic.getInputStream();
				Map<String, Object> uploadByInputStream = OSSUtils.uploadByInputStream(inputStream, pox, "CLYJ/USER/");
				cns.setCorporateBankCardPic(uploadByInputStream.get("path").toString());
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		if (corporateBankCardPic != null) {
			//文档上传oss
			try {
				String fileName = corporateBankCardPic.getOriginalFilename();
				String pox = fileName.substring(fileName.lastIndexOf(".") + 1);
				InputStream inputStream = corporateBankCardPic.getInputStream();
				Map<String, Object> uploadByInputStream = OSSUtils.uploadByInputStream(inputStream, pox, "CLYJ/USER/");
				cns.setCorporateBankCardPic(uploadByInputStream.get("path").toString());
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		if (headPicture != null) {
			//文档上传oss
			try {
				String fileName = headPicture.getOriginalFilename();
				String pox = fileName.substring(fileName.lastIndexOf(".") + 1);
				InputStream inputStream = headPicture.getInputStream();
				Map<String, Object> uploadByInputStream = OSSUtils.uploadByInputStream(inputStream, pox, "CLYJ/USER/");
				cns.setHeadPicture(uploadByInputStream.get("path").toString());
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		if (pictureIn != null) {
			//文档上传oss
			try {
				String fileName = pictureIn.getOriginalFilename();
				String pox = fileName.substring(fileName.lastIndexOf(".") + 1);
				InputStream inputStream = pictureIn.getInputStream();
				Map<String, Object> uploadByInputStream = OSSUtils.uploadByInputStream(inputStream, pox, "CLYJ/USER/");
				cns.setPictureIn(uploadByInputStream.get("path").toString());
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		if (corporateCardPicBack != null) {
			//文档上传oss
			try {
				String fileName = pictureIn.getOriginalFilename();
				String pox = fileName.substring(fileName.lastIndexOf(".") + 1);
				InputStream inputStream = pictureIn.getInputStream();
				Map<String, Object> uploadByInputStream = OSSUtils.uploadByInputStream(inputStream, pox, "CLYJ/USER/");
				cns.setCorporateCardPicBack(uploadByInputStream.get("path").toString());
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		if (threeCardPic != null) {
			//文档上传oss
			try {
				String fileName = pictureIn.getOriginalFilename();
				String pox = fileName.substring(fileName.lastIndexOf(".") + 1);
				InputStream inputStream = pictureIn.getInputStream();
				Map<String, Object> uploadByInputStream = OSSUtils.uploadByInputStream(inputStream, pox, "CLYJ/USER/");
				cns.setThreeCardPic(uploadByInputStream.get("path").toString());
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		Integer i = clyjNearbyShopsMapper.insert(cns);
		if (i>0) {
			return true;
		}
		return false;
	}
}
